# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
@Time       : 2020/7/31
@Author     : Vic
@FileName   : snake.py
@Software   : Pycharm
@ProjectName: 贪吃蛇

"""


import pygame
from pygame.locals import *
import copy
import math
import json
import random
import sys
import os

G_ERR = -1
G_OK = 0
StartSnakeLength = random.randint(4, 6)


class Snake:
    def __init__(self, map_size=40):
        self.size = map_size
        self.unit = 18
        self.timer_refresh = USEREVENT
        self.refresh_time = 30
        self.title = 'We Are Snake ! We all like eating ! '
        self.panel_width = 200
        self.border_width = 30

        self.range_x = [self.border_width, self.border_width + (self.size - 1) * self.unit]
        self.range_y = [self.border_width, self.border_width + (self.size - 1) * self.unit]

        self.panel_x = [self.border_width + (self.size - 1) * self.unit,
                        self.border_width + (self.size - 1) * self.unit + self.panel_width]
        self.panel_y = [self.border_width, self.border_width + (self.size - 1) * self.unit]

        self.WINDOW_WIDTH = self.border_width * 2 \
                            + self.panel_width \
                            + (self.size - 1) * self.unit
        self.WINDOW_HEIGHT = self.border_width * 2 \
                             + (self.size - 1) * self.unit
        self.guanka = 1
        self.snake_stack = []
        self.direction = K_FIRST
        self.direction_next = K_FIRST
        self.FOODS_NUM = 1
        self.foods = []
        self.snake_turn = [[None, None], None]
        self.fx = [4, None]
        self.status = 0
        self.time_go = 0
        self.time_cnt = 5
        self.eat_num = 0
        self.StartSnakeLength = random.randint(4, 6)

        self.his_data = None
        try:
            fp = open('data.json', 'r', encoding='utf-8')
            self.his_data = json.load(fp)
        except FileNotFoundError:
            self.his_data = {'max': {'time': 0, 'foods': 0, 'score': 0}}
            with open('data.json', 'w') as f:
                json.dump(self.his_data, f)

        self.__game_init()

    # 绘制棋盘
    def __draw_map(self):
        # 绘制棋盘
        POS_START = [self.border_width, self.border_width]
        pygame.draw.rect(self.screen, (0, 0, 0),
                         [self.border_width, self.border_width,
                          self.unit * (self.size - 1), self.unit * (self.size - 1)])

        s_font = pygame.font.SysFont('arial', 16)

        # 绘制围墙
        # 绘制行
        for item in range(1, self.size):
            self.screen.blit(self.img_wall, [self.unit * item + (self.unit / 2) + 2, self.unit * 0 + 11])
            self.screen.blit(self.img_wall, [self.unit * item + (self.unit / 2) + 2, self.unit * self.size + 11])

        # 绘制列
        for item in range(1, self.size):
            self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * item + (self.unit / 2) + 2])
            self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * item + (self.unit / 2) + 2])

        # 补全空白
        self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * self.size + 11])  # 右下角
        self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * self.size + 11])  # 左下角
        self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * 0 + 11])  # 右上角
        self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * 0 + 11])  # 左上角

    def dcsy(self, list):
        for i in range(len(list) - 1):
            if i != 0:
                if math.fabs(list[i] - list[i + 1]) == 1 and math.fabs(list[i - 1] - list[i]) != 1 and math.fabs(
                        list[i + 1] - list[i + 2]) != 1:
                    self.guai.append(self.snake_stack[list[i]])
                    self.guai.append(self.snake_stack[list[i + 1]])
            try:
                if i == 0:
                    if math.fabs(list[i] - list[i + 1]) == 1 and math.fabs(list[i + 1] - list[i + 2]) != 1:
                        self.guai.append(self.snake_stack[list[i]])
                        self.guai.append(self.snake_stack[list[i + 1]])
            except:
                self.guai.append(self.snake_stack[list[i]])
                self.guai.append(self.snake_stack[list[i + 1]])
            if math.fabs(list[i] - list[i + 1]) != 1:
                return False
        return True

    def __draw_snake(self):
        idx = len(self.snake_stack) - 1
        self.itemh = []
        self.iteml = []
        itemhi = []
        itemli = []
        self.guai = []
        for itt in range(self.size):
            itemhi.append([0, itt, []])
            itemli.append([0, itt, []])
        for index, item in enumerate(self.snake_stack):
            itemhi[item[1]][0] += 1
            itemli[item[0]][0] += 1
            itemhi[item[1]][2].append(index)
            itemli[item[0]][2].append(index)
        for item in itemli:
            if item[0] > 1 and self.dcsy(item[2]):
                for itemxy in self.snake_stack:
                    if itemxy[0] == item[1]:
                        self.iteml.append(itemxy)
        for item in itemhi:
            if item[0] > 1 and self.dcsy(item[2]):
                for itemxy in self.snake_stack:
                    if itemxy[1] == item[1]:
                        self.itemh.append(itemxy)
        for itemx in self.itemh:
            for itemy in self.iteml:
                if itemx == itemy and itemx not in self.guai:
                    self.guai.append(itemy)
        while idx >= 0:
            x = self.snake_stack[idx][0] * self.unit + self.border_width
            y = self.snake_stack[idx][1] * self.unit + self.border_width
            if idx == 0:
                self.screen.blit(self.img_head, [x - int(self.unit / 2) - 1, y - int(self.unit / 2)])
            else:
                if self.snake_stack[idx] in self.guai:
                    for i, item in enumerate(self.guai):
                        if item == self.snake_stack[idx]:
                            indexxx = i
                    try:
                        self.img_turn = self.turn(self.guai[indexxx], self.snake_stack)
                        self.screen.blit(self.img_turn, [x - int(self.unit / 2) - 1, y - int(self.unit / 2)])
                    except:
                        self.screen.blit(self.img_body, [x - int(self.unit / 2) - 1, y - int(self.unit / 2)])
                else:
                    self.screen.blit(self.img_body, [x - int(self.unit / 2) - 1, y - int(self.unit / 2)])
            idx -= 1

    def __draw_foods(self):
        for item in self.foods:
            x = item[0] * self.unit + self.border_width
            y = item[1] * self.unit + self.border_width
            t = item[2]

            if t == 1:
                self.screen.blit(self.img_apple1, [x - self.apple_size[0] / 2, y - self.apple_size[1] / 2])
            elif t == 2:
                self.screen.blit(self.img_apple2, [x - self.apple_size[0] / 2, y - self.apple_size[1] / 2])
            elif t == 3:
                self.screen.blit(self.img_apple3, [x - self.apple_size[0] / 2, y - self.apple_size[1] / 2])
            else:
                print("Error")

    def __get_score(self):
        return self.eat_num * 100 + int(self.time_go * self.refresh_time / 1000) * 2

    def __draw_panel_(self):
        pygame.draw.rect(self.screen, (255, 255, 255),
                         [self.panel_x[0] + 30, 0,
                          1000, 1000])

        self.panel_font = pygame.font.SysFont("arial", 20)

        self.surface = self.panel_font.render('Time:' + str(self.time_go * self.refresh_time / 1000) + ' S', False,
                                              (0, 0, 0))
        self.screen.blit(self.surface, [self.panel_x[0] + 50, self.panel_y[0] + 50])

        self.surface = self.panel_font.render('Fool:' + str(self.eat_num), False, (0, 0, 0))
        self.screen.blit(self.surface, [self.panel_x[0] + 50, self.panel_y[0] + 100])

        self.surface = self.panel_font.render(
            'Score: ' + str(self.__get_score()),
            False, (0, 0, 0))
        self.screen.blit(self.surface, [self.panel_x[0] + 50, self.panel_y[0] + 150])

        self.surface = self.panel_font.render(
            f'Best Score: {self.his_data["max"]["score"]}',
            False, (0, 0, 0))
        self.screen.blit(self.surface, [self.panel_x[0] + 50, self.panel_y[0] + 200])

        offset_x = self.panel_x[0] + 50
        offset_y = self.panel_y[0] + 400
        btn_h = 50
        btn_w = 150
        btn_gap = 20
        self.BTN_RANGE_NEW_START_X = [offset_x, offset_x + btn_w]
        self.BTN_RANGE_NEW_START_Y = [offset_y, offset_y + btn_h]
        exit_button = pygame.image.load("img/restart.png")
        self.screen.blit(exit_button, (780, 420))

        self.BTN_RANGE_EXIT_GAME_X = [offset_x, offset_x + btn_w]
        self.BTN_RANGE_EXIT_GAME_Y = [offset_y + btn_h + btn_gap,
                                      offset_y + btn_h + btn_gap + btn_h]
        exit_button = pygame.image.load("img/exit.png")
        self.screen.blit(exit_button, (780, 500))

    def __redraw_all(self, flag):
        if flag == 1:
            self.screen.fill((255, 255, 255))
            pygame.draw.rect(self.screen, (0, 0, 0),
                             [self.border_width, self.border_width,
                              self.unit * (self.size - 1), self.unit * (self.size - 1)])
            for item in range(1, self.size):
                self.screen.blit(self.img_wall, [self.unit * item + (self.unit / 2) + 2, self.unit * 0 + 11])
                self.screen.blit(self.img_wall, [self.unit * item + (self.unit / 2) + 2, self.unit * self.size + 11])
            for item in range(1, self.size):
                self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * item + (self.unit / 2) + 2])
                self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * item + (self.unit / 2) + 2])
            self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * self.size + 11])  # 右下角
            self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * self.size + 11])  # 左下角
            self.screen.blit(self.img_wall, [self.unit * self.size + 11, self.unit * 0 + 11])  # 右上角
            self.screen.blit(self.img_wall, [self.unit * 0 + 11, self.unit * 0 + 11])  # 左上角
            for i, item in enumerate(self.ininng["array"]):
                for j, item2 in enumerate(item):
                    if item2 == 2:
                        self.screen.blit(self.img_wall, [self.unit * j + 21, self.unit * i + 21])
            self.__draw_snake()
            self.__draw_foods()
            self.__draw_panel_()
        if flag == 2:
            self.screen.fill((255, 255, 255))
            self.__draw_map()
            self.__draw_snake()
            self.__draw_foods()
            self.__draw_panel_()

    def __game_init(self):
        pygame.init()
        self.screen = pygame.display.set_mode((self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        pygame.display.set_caption(self.title)
        self.screen.fill((255, 255, 255))
        background = pygame.image.load(os.getcwd() + "/" + "img/bg.png")
        self.screen.blit(background, (0, 0))
        ico = pygame.image.load(os.getcwd() + "/" + "img/ico.ico")
        pygame.display.set_icon(ico)
        self.sound_eat = pygame.mixer.Sound('3.wav')
        self.sound_eat.set_volume(0.2)
        self.sound_game_over = pygame.mixer.Sound('1.wav')
        self.sound_game_over.set_volume(0.5)
        self.sound_win = pygame.mixer.Sound('4.wav')
        self.sound_game_over.set_volume(0.5)
        self.sound_den = pygame.mixer.Sound('2.wav')
        pygame.mixer.music.load('bg.wav')
        pygame.mixer.music.set_volume(0.3)
        pygame.mixer.music.play(-1, 0)

        self.bg = pygame.image.load(os.getcwd() + "/" + "img/bg.png")
        self.img_turn = pygame.image.load(os.getcwd() + "/" + 'img/turn.png')
        self.img_head = pygame.image.load(os.getcwd() + "/" + 'img/head.png')
        self.img_body = pygame.image.load(os.getcwd() + "/" + 'img/body.png')
        self.img_wall = pygame.image.load(os.getcwd() + "/" + 'img/wall.png')
        self.apple_size = [12, 15]
        self.img_apple1 = pygame.image.load(os.getcwd() + "/" + 'img/apple_1.png')
        self.img_apple2 = pygame.image.load(os.getcwd() + "/" + 'img/apple_2.png')
        self.img_apple3 = pygame.image.load(os.getcwd() + "/" + 'img/apple_3.png')
        self.img_head_up = self.img_head
        self.img_head_right = pygame.transform.rotate(self.img_head, 270)
        self.img_head_down = pygame.transform.rotate(self.img_head, 180)
        self.img_head_left = pygame.transform.rotate(self.img_head, 90)
        self.img_head = self.img_head_right

        self.img_turn_up = self.img_turn
        self.img_turn_right = pygame.transform.rotate(self.img_turn, 270)
        self.img_turn_down = pygame.transform.rotate(self.img_turn, 180)
        self.img_turn_left = pygame.transform.rotate(self.img_turn, 90)
        self.img_turn = self.img_turn_right

    def __do_new_start(self, flag):
        self.__init__()
        self.status = 1
        if flag == 1:
            self.cstart()
        if flag == 2:
            self.startendless()

    def __do_btn_(self, pos, flag):
        # 是否点击了按钮
        if self.BTN_RANGE_NEW_START_X[0] < pos[0] < self.BTN_RANGE_NEW_START_X[1] \
                and self.BTN_RANGE_NEW_START_Y[0] < pos[1] < self.BTN_RANGE_NEW_START_Y[1]:
            self.__do_new_start(flag)
            return G_OK
        elif self.BTN_RANGE_EXIT_GAME_X[0] < pos[0] < self.BTN_RANGE_EXIT_GAME_X[1] \
                and self.BTN_RANGE_EXIT_GAME_Y[0] < pos[1] < self.BTN_RANGE_EXIT_GAME_Y[1]:
            self.start()
        else:
            return G_ERR

    def turn(self, list, snake):
        index = 0
        for i, item in enumerate(snake):
            if item == list:
                index = i
        indexfront = snake[index - 1]
        indexnext = snake[index + 1]
        if indexfront[1] == list[1] - 1 or indexnext[1] == list[1] - 1:
            if indexfront[0] == list[0] - 1 or indexnext[0] == list[0] - 1:
                return self.img_turn_up
            if indexfront[0] == list[0] + 1 or indexnext[0] == list[0] + 1:
                return self.img_turn_right
        if indexfront[1] == list[1] + 1 or indexnext[1] == list[1] + 1:
            if indexfront[0] == list[0] - 1 or indexnext[0] == list[0] - 1:
                return self.img_turn_left
            if indexfront[0] == list[0] + 1 or indexnext[0] == list[0] + 1:
                return self.img_turn_down

    def __do_change_direction(self, key):
        if self.status != 1:
            return
        if key not in [K_LEFT, K_RIGHT, K_UP, K_DOWN]:
            return
        if (self.direction == K_LEFT or self.direction == K_RIGHT) \
                and (key == K_LEFT or key == K_RIGHT):
            return
        if (self.direction == K_UP or self.direction == K_DOWN) \
                and (key == K_UP or key == K_DOWN):
            return
        self.direction_next = key

        if key == K_UP:
            self.img_head = self.img_head_up
        elif key == K_DOWN:
            self.img_head = self.img_head_down
        elif key == K_LEFT:
            self.img_head = self.img_head_left
        elif key == K_RIGHT:
            self.img_head = self.img_head_right
        else:
            self.img_head = self.img_head_right

    def __do_pause(self):
        if self.status == 1:
            self.status = 2
            pygame.mixer.music.pause()
        elif self.status == 2:
            self.status = 1
            pygame.mixer.music.unpause()

    def __do_move(self):
        tmp1 = copy.deepcopy(self.snake_stack[0])
        if self.direction_next != K_FIRST:
            self.direction = self.direction_next
        else:
            self.direction_next = K_FIRST
        if self.direction == K_RIGHT:
            self.snake_stack[0][0] += 1
        if self.direction == K_LEFT:
            self.snake_stack[0][0] -= 1
        if self.direction == K_UP:
            self.snake_stack[0][1] -= 1
        if self.direction == K_DOWN:
            self.snake_stack[0][1] += 1
        idx = 1
        while idx < len(self.snake_stack):
            tmp2 = copy.deepcopy(self.snake_stack[idx])
            self.snake_stack[idx] = copy.deepcopy(tmp1)
            tmp1 = copy.deepcopy(tmp2)
            idx += 1

    def __check_game_over(self, flag):
        if self.snake_stack[0] in self.snake_stack[1:]:
            return True
        if self.snake_stack[0][0] >= self.size - 1 \
                or self.snake_stack[0][1] >= self.size - 1 \
                or self.snake_stack[0][0] <= 0 \
                or self.snake_stack[0][1] <= 0:
            return True
        if flag == 1:
            for i, itemi in enumerate(self.ininng["array"]):
                for j, item in enumerate(itemi):
                    if self.snake_stack[0] == list((j, i)) and item == 2:
                        return True
        return False

    def __give_food(self):
        self.FOODS_NUM = 1
        tmp_foods = [[tmp[0], tmp[1]] for tmp in self.foods]
        for i in range(1, 40):
            food_pos = [random.randint(1, self.size - 5), random.randint(1, self.size - 5)]
            if food_pos not in self.snake_stack \
                    and food_pos not in tmp_foods:
                index = random.random()
                if index < 0.2:
                    indext = 3
                elif index > 0.7:
                    indext = 2
                else:
                    indext = 1
                food = [food_pos[0], food_pos[1], indext]
                self.foods.append(food)
                tmp_foods.append(food_pos)
                if len(self.foods) >= self.FOODS_NUM:
                    break

    def __do_eat_food(self, pos, flag):
        tmp_foods = [[item[0], item[1]] for item in self.foods]
        tmp_foods_type = [[itemt[0], itemt[1], itemt[2]] for itemt in self.foods]
        if self.snake_stack[0] not in tmp_foods:
            return
        idx = tmp_foods.index(self.snake_stack[0])
        self.eat_num += tmp_foods_type[idx][2]
        self.foods.pop(idx)
        if flag == 2:
            self.__give_food()
        self.snake_stack.append(pos)
        self.sound_eat.play()

    def __game_over(self, flag):
        pygame.mixer.music.stop()
        self.sound_game_over.play()
        self.screen.fill((255, 255, 255))
        self.status = 0
        self.game_over_font = pygame.font.SysFont('Times New Roman', 80)
        surface = self.game_over_font.render(f'game over', False, (255, 255, 255))
        game_over_img = pygame.image.load("img/game_over.png")
        self.screen.blit(game_over_img,
                         [int(self.range_x[0] + self.unit * (self.size - 1) / 4 - 170),
                          int(self.range_y[0] + self.unit * (self.size - 1) / 4 - 200)])
        self.game_over_font = pygame.font.SysFont('宋体', 60)
        surface = self.game_over_font.render(f'{self.__get_score()}', False, (0, 0, 0))
        self.screen.blit(surface,
                         [int(self.range_x[0] + self.unit * (self.size - 1)) / 2,
                          int(self.range_y[0] + self.unit * (self.size - 1)) - 130])
        surface = self.game_over_font.render(
            str(round(self.time_go * self.refresh_time / 1000 - 0.15, 2)) + ' S',
            False, (0, 0, 0))
        self.screen.blit(surface,
                         [int(self.range_x[0] + self.unit * (self.size - 1)) / 2,
                          int(self.range_y[0] + self.unit * (self.size - 1)) / 1.43])

        data = {'max': {'time': self.time_go,
                        'foods': self.eat_num,
                        'score': self.__get_score()},
                "v": {"ininngs": "1", "huei": 0}
                }
        if flag != 1:
            if self.his_data is None \
                    or data['max']['score'] > self.his_data['max']['score']:
                with open('data.json', 'w') as fp:
                    json.dump(data, fp)
                New_record = pygame.image.load("img/new_r.png")
                self.screen.blit(New_record,
                                 [int(self.range_x[0] + self.unit * (self.size - 1) / 2 + 200),
                                  int(self.range_y[0] + self.unit * (self.size - 1) / 2 - 50)])
        restart = pygame.image.load("img/restart.png")
        restart = pygame.transform.smoothscale(restart, (280, 100))
        exit = pygame.image.load("img/exit.png")
        exit = pygame.transform.smoothscale(exit, (280, 100))
        self.screen.blit(restart, (550, 500))
        self.screen.blit(exit, (550, 650))
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.pos[0] >= 558 and event.pos[0] <= 819 and event.pos[1] >= 506 and event.pos[1] <= 590:
                        self.__do_new_start(2)
                    if event.pos[0] >= 556 and event.pos[0] <= 814 and event.pos[1] >= 688 and event.pos[1] <= 703:
                        self.start()
            pygame.display.flip()

    def game_win(self):
        pygame.mixer.music.stop()
        self.sound_win.play()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                self.screen.fill((255, 255, 255))
                self.status = 0
                win_img = pygame.image.load("img/win.png")
                self.screen.blit(win_img,
                                 [int(self.range_x[0] + self.unit * (self.size - 1) / 4 - 170),
                                  int(self.range_y[0] + self.unit * (self.size - 1) / 4 - 200)])
                self.game_over_font = pygame.font.SysFont('宋体', 60)
                surface = self.game_over_font.render(f'{self.__get_score()}', False, (0, 0, 0))
                self.screen.blit(surface,
                                 [int(self.range_x[0] + self.unit * (self.size - 1)) / 2,
                                  int(self.range_y[0] + self.unit * (self.size - 1)) - 130])
                surface = self.game_over_font.render(
                    str(round(self.time_go * self.refresh_time / 1000 - 0.15, 2)) + ' S',
                    False, (0, 0, 0))
                self.screen.blit(surface,
                                 [int(self.range_x[0] + self.unit * (self.size - 1)) / 2,
                                  int(self.range_y[0] + self.unit * (self.size - 1)) / 1.43])

                restart = pygame.image.load("img/restart.png")
                restart = pygame.transform.smoothscale(restart, (280, 100))
                exit = pygame.image.load("img/exit.png")
                exit = pygame.transform.smoothscale(exit, (280, 100))
                self.screen.blit(restart, (550, 500))
                self.screen.blit(exit, (550, 650))
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        sys.exit()
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        if event.pos[0] >= 558 and event.pos[0] <= 819 and event.pos[1] >= 506 and event.pos[1] <= 590:
                            self.__do_new_start(2)
                        if event.pos[0] >= 556 and event.pos[0] <= 814 and event.pos[1] >= 688 and event.pos[1] <= 703:
                            self.start()

            pygame.display.flip()

    def __change_rate(self):
        score = self.__get_score()

        if score < 1000:
            self.time_cnt = 5
        elif score < 5000:
            self.time_cnt = 4
        elif score < 10000:
            self.time_cnt = 3
        elif score < 50000:
            self.time_cnt = 2
        else:
            self.time_cnt = 1

    def __refresh(self, flag):
        if self.status != 1:
            return
        self.time_go += 1

        self.time_cnt -= 1
        if self.time_cnt > 0:
            return
        else:
            self.__change_rate()

        snake_last = copy.deepcopy(self.snake_stack[-1])

        self.__do_move()

        if flag == 2:
            self.__do_eat_food(snake_last, 2)
            if len(self.foods) == 0:
                self.__give_food()
        if flag == 1:
            self.__do_eat_food(snake_last, 1)
            if len(self.foods) == 0:
                self.game_win()

        self.__redraw_all(flag)

        if flag == 1:
            if len(self.foods) == 0:
                self.game_win()

        if self.__check_game_over(flag):
            self.__game_over(flag)

    def cstart(self):
        tife = True
        c = pygame.image.load("img/c.png")
        self.screen.blit(c, (0, 0))
        while tife:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.pos[0] >= 170 and event.pos[0] <= 341 and event.pos[1] >= 156 and event.pos[1] <= 259:
                        self.guanka = 1
                        self.startinnings()
                        return
                    if event.pos[0] >= 400 and event.pos[0] <= 600 and event.pos[1] >= 156 and event.pos[1] <= 259:
                        self.guanka = 2
                        self.startinnings()
                    if event.pos[0] >= 645 and event.pos[0] <= 808 and event.pos[1] >= 156 and event.pos[1] <= 259:
                        self.guanka = 3
                        print(2)
                        self.startinnings()
                        print(3)
            pygame.display.flip()

    def startendless(self):
        self.__game_init()
        self.img_head = self.img_head_right
        self.foods.clear()
        self.snake_stack.clear()
        i = StartSnakeLength
        for index in range(StartSnakeLength):
            self.snake_stack.append([i + 1, 2])
            i -= 1
        self.direction = K_RIGHT
        pygame.time.set_timer(self.timer_refresh, self.refresh_time)
        self.__redraw_all(2)
        number_food = random.randint(10, 15)
        while number_food:
            self.__give_food()
            number_food -= 1
        self.status = 1
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == self.timer_refresh:
                    self.__refresh(2)
                if event.type == MOUSEBUTTONUP:
                    self.__do_btn_(event.pos, 2)
                if event.type == KEYDOWN:
                    if event.key == K_s:
                        self.__do_pause()
                    else:
                        self.__do_change_direction(event.key)

            pygame.display.update()

    def startinnings(self):
        self.foods.clear()
        self.ininng = json.load((open(("innings/" + str(self.guanka) + ".json"), 'r', encoding='utf-8')))
        for i, item in enumerate(self.ininng["array"]):
            for j, item2 in enumerate(item):
                if item2 == 3:
                    food = [j, i, 1]
                    self.foods.append(food)
                if item2 == 4:
                    food = [j, i, 2]
                    self.foods.append(food)
                if item2 == 5:
                    food = [j, i, 3]
                    self.foods.append(food)
        self.snake_stack.clear()
        i = StartSnakeLength
        for index in range(StartSnakeLength):
            self.snake_stack.append([i + 1, 2])
            i -= 1
        self.direction = K_RIGHT
        pygame.time.set_timer(self.timer_refresh, self.refresh_time)
        self.__redraw_all(1)
        self.status = 1
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == self.timer_refresh:
                    self.__refresh(1)
                if event.type == MOUSEBUTTONUP:
                    self.__do_btn_(event.pos, 1)
                if event.type == KEYDOWN:
                    if event.key == K_s:
                        self.__do_pause()
                    else:
                        self.__do_change_direction(event.key)

            pygame.display.update()

    def start(self):
        background = pygame.image.load(r"img/bg.png")
        self.screen.blit(background, (0, 0))

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                button_image = pygame.image.load("img/begin.png")
                button_image2 = pygame.image.load("img/cg.png")
                self.screen.blit(button_image, (100, 500, 50, 50))
                self.screen.blit(button_image2, (480, 500, 50, 50))
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.pos[0] >= 113 and event.pos[0] <= 441 and event.pos[1] >= 508 and event.pos[1] <= 637:
                        self.__do_new_start(2)
                    if event.pos[0] >= 487 and event.pos[0] <= 868 and event.pos[1] >= 507 and event.pos[1] <= 634:
                        self.__do_new_start(1)
            pygame.display.flip()


if __name__ == '__main__':
    inst1 = Snake()
    inst1.start()
